//
//  SSNXMLParser.m
//  SSNDB
//
//  Created by nako on 9/21/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SSNXMLParser.h"
#import "SSNDBAppDelegate.h"

@implementation SSNXMLParser

- (SSNXMLParser *) initXMLParser {
	
	[super init];
	
	appDelegate = (SSNDBAppDelegate*)[[UIApplication sharedApplication] delegate];
	//aPerson = nil;
	//aContact = nil;
	return self;
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName 
	attributes:(NSDictionary *)attributeDict {
	
	//NSLog(@"Processing Element: %@", elementName);
	if ([elementName isEqualToString:@"Persons"]) {
		//NSLog(@"Persons");
	}else if([elementName isEqualToString:@"Person"]){
		if (aPerson != nil) {
			NSLog(@"What the...");
			[aPerson release];
			aPerson = nil;
		}
		aPerson = [[Person alloc] init];
		//ID = [[attributeDict objectForKey:@"id"] integerValue];
	}else if ([elementName isEqualToString:@"Contacts"]) {
		//NSLog(@"Contacts");
	}else if ([elementName isEqualToString:@"Contact"]){
		if (aContact != nil) {
			NSLog(@"What the...");
			[aContact release];
			aContact = nil;
		}
		aContact = [[Contact alloc] init];
	}else if ([elementName isEqualToString:@"SSNDB"]){
		NSLog(@"SSNDB");
	}else{
		curElement = [[NSString alloc] initWithString:elementName];
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 
	
	if ( curElement != nil) {
		if(currentElementValue == nil) 
			currentElementValue = [[NSMutableString alloc] initWithString:string];
		else
			[currentElementValue appendString:string];
		//NSLog(@"found char Value: %@", currentElementValue);
	}
	
	
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	if ([elementName isEqualToString:@"SSNDB"])
		return;
	
	if ([elementName isEqualToString:@"Person"]) {
		[appDelegate.persons addObject:aPerson];
		[aPerson release];
		aPerson = nil;
	}else if ([elementName isEqualToString:@"Contact"]) {
		[appDelegate.contacts addObject:aContact];
		[aContact release];
		aContact = nil;
	}else if (aPerson != nil){ 
		//NSLog(@"%@",elementName);
		[aPerson setValue:currentElementValue forKey:elementName];
		[curElement release];
		curElement = nil;
	}else if (aContact != nil){
		[aContact setValue:currentElementValue forKey:elementName];
		[curElement release];
		curElement = nil;
	}
			   
	[currentElementValue release];
	currentElementValue = nil;
	//NSLog(@"Processing Element End :%@",elementName);
}

- (void) dealloc {
	
	[aPerson release];
	[aContact release];
	[curElement release];
	[currentElementValue release];
	[super dealloc];
}


@end
